//
//  BVHomeViewController.m
//  BVHomeScene
//
//  Created by 崔晋 on 2019/8/11.
//

#import "BVHomeViewController.h"
#import "BVHomeSceneHeaderView.h"
#import "Masonry.h"
#import "BVService.h"
#import "BVMetaModel.h"

#import "BVHomeFirstTableViewCell.h"
#import "BVHomeNormalTableViewCell.h"

#import "BVHomeLocationView.h"
#import "BVLocationUtil.h"
#import "BVVideoPlayView.h"
#import "BVWorkoutModel.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "BVWorkoutDetailViewController.h"
#import "BVEditVideoViewController.h"
#import <UShareUI/UShareUI.h>
#import "BVFullScreenPlayViewController.h"
#import "UITableViewCell+BVCategort.h"

@interface BVHomeViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) BVHomeSceneHeaderView *headrView;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSArray<UITableView *> *tableViews;

@property (nonatomic, strong) NSMutableArray<BVHomeLocationView *> *locationViews;

@property (nonatomic, strong) NSMutableDictionary<NSNumber *, NSMutableArray<BVMetaModel *> *> *newDataSource;

@property (nonatomic, strong) NSMutableArray<BVWorkoutModel *> *workOutDataSource;

@property (nonatomic, strong) BVWorkoutModel *selectedWorkModel;

@property (nonatomic, strong) BVHomeFirstTableViewCell *fistCell;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) BOOL isFullScreen;

@end

@implementation BVHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupViews];
    [self makeContraints];
    [self loadData];
}

- (void)loadData {
    
    [[BVService shareInstance] get:@"workout" param:@{} complete:^(BOOL success, id  _Nullable response) {
        [SVProgressHUD dismiss];
        if (success) {
            NSArray<NSDictionary *> *dataList = response[@"data"][@"results"];
            [self handleWorkoutDataList:dataList];
            if (dataList.count == 0) {
                [self errorView];
            }
        }else {
            [self errorView];
        }
    }];
}

- (void)errorView {
    __weak typeof(self)weakSelf = self;
    [BVErrorView showWithType:BVErrorViewTypeHome inView:self.view retryBlock:^{
        [weakSelf loadData];
    }];
}

- (void)handleWorkoutDataList:(NSArray<NSDictionary *> *)datalist {
    self.workOutDataSource = [BVWorkoutModel arrayOfModelsFromDictionaries:datalist error:nil];
    [self.workOutDataSource sortUsingComparator:^NSComparisonResult(BVWorkoutModel *  _Nonnull obj1, BVWorkoutModel *  _Nonnull obj2) {
        return [obj2.enterAt.date compare:obj1.enterAt.date];
    }];
    NSMutableArray<BVWorkoutModel *> *deleteArray = [NSMutableArray array];
    for (int i = 0; i < self.workOutDataSource.count; i++) {
        BVWorkoutModel *baseWorkOutModel = self.workOutDataSource[i];
        for (int j = i + 1; j < self.workOutDataSource.count; j++) {
            BVWorkoutModel *compareModel = self.workOutDataSource[j];
            if (![deleteArray containsObject:compareModel] &&
                [compareModel.enterAt.date isSameDay:baseWorkOutModel.enterAt.date]) {
                [deleteArray addObject:compareModel];
            }
        }
    }
    [self.workOutDataSource removeObjectsInArray:deleteArray];
    self.headrView.dataSource = self.workOutDataSource;
    [self setupTableViews];
    self.selectedWorkModel = self.workOutDataSource.firstObject;
    
}

- (void)handleDataList:(NSArray<NSDictionary *> *)dataList withIndex:(NSInteger)index {
    NSMutableArray *dataSource = [BVMetaModel arrayOfModelsFromDictionaries:dataList error:nil];
    [self.newDataSource setObject:dataSource forKey:@(index)];
    [self.tableViews[index] reloadData];
}

- (void)playVideoWithIndexPath:(NSIndexPath *)indexPath model:(BVMetaModel *)model{
    [self.fistCell setPlaying:NO];
    if (indexPath.row == 0) {
        BVHomeFirstTableViewCell *cell = [self.tableViews[self.page] cellForRowAtIndexPath:indexPath];
        if (cell.isPlaying) {
            [cell setPlaying:YES];
            return;
        }
        BVVideoPlayView *view = [BVVideoPlayView sharedInstance];
        [cell.backgroundImageView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(cell.containerView);
        }];
        [cell setPlaying:YES];
        view.url = [model.video buildUrlString];
        [view.playController prepareToPlay];
        [view.playController play];
        __weak typeof(self)weakSelf = self;
        dispatch_block_t fullScreenBlock = ^{
            [weakSelf fullScreenWithCell:cell];
        };
        [[BVVideoPlayView sharedInstance] setFullScreenBlock:fullScreenBlock];
        return;
    }
    BVHomeNormalTableViewCell *cell = [self.tableViews[self.page] cellForRowAtIndexPath:indexPath];
    if (cell.isPlaying) {
        return;
    }
    BVVideoPlayView *view = [BVVideoPlayView sharedInstance];
    [cell.backImageView addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(cell.backImageView);
    }];
    view.url = [model.video buildUrlString];
    [view.playController prepareToPlay];
    [view.playController play];
    __weak typeof(self)weakSelf = self;
    [[BVVideoPlayView sharedInstance] setFullScreenBlock:^{
        [weakSelf fullScreenWithNormalCell:cell];
    }];
}


- (void)fullScreenWithCell:(UITableViewCell *)cell {
    BVFullScreenPlayViewController *vc = [[BVFullScreenPlayViewController alloc] initWithNibName:@"BVFullScreenPlayViewController" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]];
    BVHomeFirstTableViewCell *firstCell = nil;
    if ([cell isKindOfClass:[BVHomeFirstTableViewCell class]]) {
        firstCell = (BVHomeFirstTableViewCell *)cell;
    }else {
        return;
    }
    __weak typeof(self)weakSelf = self;
    dispatch_block_t dismissBlock = ^{
        BVVideoPlayView *view = [BVVideoPlayView sharedInstance];
        [view removeFromSuperview];
        [view setFullScreenBlock:^{
            [weakSelf fullScreenWithCell:cell];
        }];
        [firstCell.backgroundImageView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(firstCell.containerView);
        }];
        
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = UIInterfaceOrientationMaskPortrait;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSInteger index = self.headrView.page;
                weakSelf.scrollView.contentOffset = CGPointMake(index * kSCREEN_WIDTH, 0);
            });
        }
    };
    
    [vc setDismissBlock:dismissBlock];
    vc.playView = [BVVideoPlayView sharedInstance];
    [weakSelf presentViewController:vc animated:NO completion:nil];
}

- (void)fullScreenWithNormalCell:(UITableViewCell *)cell {
    BVFullScreenPlayViewController *vc = [[BVFullScreenPlayViewController alloc] initWithNibName:@"BVFullScreenPlayViewController" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]];
    BVHomeNormalTableViewCell *firstCell = nil;
    if ([cell isKindOfClass:[BVHomeNormalTableViewCell class]]) {
        firstCell = (BVHomeNormalTableViewCell *)cell;
    }else {
        return;
    }
    __weak typeof(self)weakSelf = self;
    dispatch_block_t dismissBlock = ^{
        BVVideoPlayView *view = [BVVideoPlayView sharedInstance];
        [view removeFromSuperview];
        [view setFullScreenBlock:^{
            [weakSelf fullScreenWithNormalCell:cell];
        }];
        [firstCell.backImageView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(firstCell.backImageView);
        }];
        
        if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
            SEL selector = NSSelectorFromString(@"setOrientation:");
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
            [invocation setSelector:selector];
            [invocation setTarget:[UIDevice currentDevice]];
            int val = UIInterfaceOrientationMaskPortrait;
            [invocation setArgument:&val atIndex:2];
            [invocation invoke];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSInteger index = self.headrView.page;
                weakSelf.scrollView.contentOffset = CGPointMake(index * kSCREEN_WIDTH, 0);
            });
        }
    };
    
    [vc setDismissBlock:dismissBlock];
    vc.playView = [BVVideoPlayView sharedInstance];
    [weakSelf presentViewController:vc animated:NO completion:nil];
}



- (void)setupViews {
    [self.view addSubview:self.headrView];
    [self.view addSubview:self.scrollView];
}

- (void)makeContraints {
    [self.headrView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.top.equalTo(self.view);
        make.height.mas_equalTo(kNavigationBarHeight);
    }];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.equalTo(self.view);
        make.top.equalTo(self.headrView.mas_bottom);
    }];
    
}

- (void)setupTableViews {
    NSMutableArray<UITableView *> *temptTableViews = [NSMutableArray array];
    [self.workOutDataSource enumerateObjectsUsingBlock:^(BVWorkoutModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        tableView.backgroundColor = [UIColor whiteColor];
        tableView.delegate = self;
        tableView.dataSource = self;
        
        [tableView registerNib:[UINib nibWithNibName:@"BVHomeFirstTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVHomeFirstTableViewCell"];
        [tableView registerNib:[UINib nibWithNibName:@"BVHomeNormalTableViewCell" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]] forCellReuseIdentifier:@"BVHomeNormalTableViewCell"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH, 55)];
        tableView.tableHeaderView = view;
        tableView.tag = idx;
        [temptTableViews addObject:tableView];
        
        
        NSBundle *bundle = [BVBundle bundleWithClass:[BVHomeViewController class] name:BV_BUNDLE_HOME_SCENE_MODULE];
        BVHomeLocationView *locationView = [bundle loadNibNamed:@"BVHomeLocationView" owner:nil options:nil].firstObject;
        locationView.moreButton.hidden = NO;
        [locationView.moreButton addTarget:self action:@selector(moreButtonAct) forControlEvents:UIControlEventTouchUpInside];
        [self.locationViews addObject:locationView];
        
    }];
    _tableViews = temptTableViews.copy;
    
    
    [self.locationViews enumerateObjectsUsingBlock:^(BVHomeLocationView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.scrollView addSubview:obj];
    }];
    
    [self.tableViews enumerateObjectsUsingBlock:^(UITableView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.scrollView addSubview:obj];
    }];
    
    __block BVHomeLocationView *lastLocationView = nil;
    [self.locationViews enumerateObjectsUsingBlock:^(BVHomeLocationView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.scrollView.mas_top);
            make.left.mas_equalTo(lastLocationView ? lastLocationView.mas_right : self.scrollView.mas_left);
            make.height.mas_equalTo(55);
            make.width.mas_equalTo(kSCREEN_WIDTH);
        }];
        lastLocationView = obj;
    }];
    
    __block UITableView *lastTableView = nil;
    [self.tableViews enumerateObjectsUsingBlock:^(UITableView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.scrollView.mas_top).offset(55);
            make.left.mas_equalTo(lastTableView ? lastTableView.mas_right : self.scrollView.mas_left);
            make.height.mas_equalTo(kSCREEN_HEIGHT - kNavigationBarHeight - kTabBarHeight - 55);
            make.width.mas_equalTo(kSCREEN_WIDTH);
            if (idx == self.tableViews.count-1) {
                make.right.mas_equalTo(self.scrollView.mas_right);
            }
        }];
        lastTableView = obj;
    }];
}

- (void)setSelectedWorkModel:(BVWorkoutModel *)selectedWorkModel {
    _selectedWorkModel = selectedWorkModel;
    if (self.workOutDataSource.count == 0) {
        return;
    }
    NSInteger index = [self.workOutDataSource indexOfObject:selectedWorkModel];
    if ([[self.newDataSource objectForKey:@(index)] isKindOfClass:[NSArray class]] &&
        [[self.newDataSource objectForKey:@(index)] count] > 0) {
        return;
    }
    [self.locationViews[index] configWithLocation:selectedWorkModel];
    
    [[BVService shareInstance] get:@"vmeta" param:@{@"workout": selectedWorkModel.objectId} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            NSArray<NSDictionary *> *dataList = response[@"data"][@"results"];
            [self handleDataList:dataList withIndex:index];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self scrollViewDidEndDecelerating:self.tableViews[index]];
            });
            if ([self.newDataSource[@(index)] count] == 0) {
                [BVErrorView showWithType:BVErrorViewTypeNoData inView:self.tableViews[index] retryBlock:^{
                    self.selectedWorkModel = selectedWorkModel;
                }];
            }
        }else {
            [BVErrorView showWithType:BVErrorViewTypeNoData inView:self.tableViews[index] retryBlock:^{
                self.selectedWorkModel = selectedWorkModel;
            }];
        }
    }];
}

- (void)favoriteWithModel:(BVMetaModel *)model {
    [SVProgressHUD show];
    [[BVService shareInstance] put:[NSString stringWithFormat:@"vmeta/%@", model.objectId] requestBodt:@{@"likes": model.likes?@"false":@"true"} complete:^(BOOL success, id  _Nullable response) {
        if (success) {
            model.likes = !model.likes;
            [SVProgressHUD showSuccessWithStatus:model.likes? @"收藏成功" : @"取消收藏成功"];
            [self.tableViews[self.page] reloadData];
        }else {
            [SVProgressHUD showErrorWithStatus:@"操作失败请重试"];
        }
    }];
}

- (void)editVideoWithModel:(BVMetaModel *)model {
    [SVProgressHUD showProgress:0];
    [[BVService shareInstance] downloadVideoWithUrl:model.video progress:^(NSProgress * _Nonnull progress) {
        [SVProgressHUD showProgress:(double)progress.completedUnitCount / (double)progress.totalUnitCount];
    } complete:^(BOOL success, NSURL * _Nullable filePath) {
        [SVProgressHUD dismiss];
        if (success) {
            BVEditVideoViewController *editVc = [[BVEditVideoViewController alloc] initWithNibName:@"BVEditVideoViewController" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]];
            editVc.videoUrl = filePath;
            editVc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:editVc animated:YES];
        }
    }];
    
}

- (void)shareVideoWithModel:(BVMetaModel*)model {
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatTimeLine), @(UMSocialPlatformType_WechatSession)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        UMSocialMessageObject *message = [UMSocialMessageObject messageObject];
        UMShareVideoObject *video = [[UMShareVideoObject alloc]init];
        video.videoUrl = [model.video buildUrlString];
        message.shareObject = video;
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:message currentViewController:self completion:^(id result, NSError *error) {
            
        }];
    }];
}

- (void)moreButtonAct {
    BVWorkoutDetailViewController *vc = [[BVWorkoutDetailViewController alloc] initWithNibName:@"BVWorkoutDetailViewController" bundle:[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]];
    vc.workoutModel = self.selectedWorkModel;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - tableview delegate and datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.newDataSource[@([self.tableViews indexOfObject:tableView])].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BVMetaModel *model = self.newDataSource[@([self.tableViews indexOfObject:tableView])][indexPath.row];
    __weak typeof(self)weakSelf = self;
    if (indexPath.row == 0) {
        BVHomeFirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVHomeFirstTableViewCell" forIndexPath:indexPath];
        [cell configWithModel:model];
        [cell setPlayBlock:^{
            [weakSelf playVideoWithIndexPath:indexPath model:model];
        }];
        self.fistCell = cell;
        cell.favoriteAct = ^{
            [weakSelf favoriteWithModel:model];
        };
        cell.editVideoActBlock = ^{
            [weakSelf editVideoWithModel:model];
        };
        [cell setShareActBlock:^{
            [weakSelf shareVideoWithModel:model];
        }];
        return cell;
    }
    BVHomeNormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BVHomeNormalTableViewCell" forIndexPath:indexPath];
    [cell configWithModel:model indexPath:indexPath];
    cell.favoriteAct = ^{
        [weakSelf favoriteWithModel:model];
    };
    [cell setEditAct:^{
        [weakSelf editVideoWithModel:model];
    }];
    [cell setShareActBlock:^{
        [weakSelf shareVideoWithModel:model];
    }];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self playVideoWithIndexPath:indexPath model:self.newDataSource[@(self.page)][indexPath.row]];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return [BVHomeFirstTableViewCell cellHeight];
    }
    return [BVHomeNormalTableViewCell cellHeight];
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[BVHomeFirstTableViewCell class]]) {
        BVHomeFirstTableViewCell *videoCell = (BVHomeFirstTableViewCell *)cell;
        [videoCell setPlaying:NO];
        [videoCell.backgroundImageView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj == [BVVideoPlayView sharedInstance]) {
                [[BVVideoPlayView sharedInstance] removeFromSuperview];
                [BVVideoPlayView sharedInstance].url = nil;
            }
        }];
    }else if ([cell isKindOfClass:[BVHomeNormalTableViewCell class]]) {
        BVHomeNormalTableViewCell *videoCell = (BVHomeNormalTableViewCell *)cell;
               [videoCell.backImageView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                   if (obj == [BVVideoPlayView sharedInstance]) {
                       [[BVVideoPlayView sharedInstance] removeFromSuperview];
                       [BVVideoPlayView sharedInstance].url = nil;
                   }
               }];
    }
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if ([scrollView isKindOfClass:[UITableView class]]) {
        if (![BVService  shareInstance].isWifi) {
            return;
        }
        NSArray *tableviewCells = [self.tableViews[self.page] visibleCells];
        
        __block UITableViewCell *cell = nil;
        
        [tableviewCells enumerateObjectsUsingBlock:^(UITableViewCell *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            CGRect rect = [obj convertRect:obj.bounds toView:[UIApplication sharedApplication].keyWindow];
            CGRect scrollRect = [scrollView convertRect:scrollView.bounds toView:[UIApplication sharedApplication].keyWindow];
            if (rect.origin.y > scrollRect.origin.y &&
                rect.origin.y + rect.size.height < scrollRect.origin.y + scrollRect.size.height + 25 + 40) {
                cell = obj;
                *stop = YES;
            }
        }];
        if (!cell) {
            
            [tableviewCells enumerateObjectsUsingBlock:^(UITableViewCell *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                CGRect rect = [obj convertRect:obj.bounds toView:[UIApplication sharedApplication].keyWindow];
                CGRect scrollRect = [scrollView convertRect:scrollView.bounds toView:[UIApplication sharedApplication].keyWindow];
                if (rect.origin.y > scrollRect.origin.y &&
                    rect.origin.y + rect.size.height < scrollRect.origin.y + scrollRect.size.height) {
                    cell = obj;
                    *stop = YES;
                }
                if ([obj isKindOfClass:[BVHomeFirstTableViewCell class]]) {
                    if (rect.origin.y > scrollRect.origin.y - 50 &&
                        rect.origin.y + rect.size.height < scrollRect.origin.y + scrollRect.size.height + 150) {
                        cell = obj;
                        *stop = YES;
                    }
                }
            }];
            if (!cell) {
                return;
            }
        }
        UITableView *tableView = self.tableViews[self.page];
        NSIndexPath *indexP = [tableView indexPathForCell:cell];
        BVMetaModel *model = self.newDataSource[@(self.page)][indexP.row];
        [self playVideoWithIndexPath:indexP model:model];
    }
    
    if (scrollView == self.scrollView) {
        self.page = self.scrollView.contentOffset.x / self.scrollView.bounds.size.width;
        self.selectedWorkModel = self.workOutDataSource[self.page];
        self.headrView.page = self.page;
    }
}


#pragma mark - 懒加载

- (BVHomeSceneHeaderView *)headrView {
    if (!_headrView) {
        _headrView = [[BVBundle bundleWithClass:self.class name:BV_BUNDLE_HOME_SCENE_MODULE]  loadNibNamed:@"BVHomeSceneHeaderView" owner:nil options:nil].firstObject;
        __weak typeof(self)weakSelf = self;
        _headrView.selectWorkOut = ^(BVWorkoutModel * _Nonnull workoutModel) {
            NSInteger index = [weakSelf.workOutDataSource indexOfObject:workoutModel];
            [UIView animateWithDuration:0.25 animations:^{
                weakSelf.scrollView.contentOffset = CGPointMake(index * kSCREEN_WIDTH, 0);
            } completion:^(BOOL finished) {
                [weakSelf scrollViewDidEndDecelerating:weakSelf.scrollView];
            }];
            
        };
    }
    return _headrView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.pagingEnabled = YES;
        _scrollView.delegate = self;
        _scrollView.showsHorizontalScrollIndicator = NO;
    }
    return _scrollView;
}

- (NSMutableDictionary<NSNumber *,NSMutableArray<BVMetaModel *> *> *)newDataSource {
    if (!_newDataSource) {
        _newDataSource = [NSMutableDictionary dictionary];
    }
    return _newDataSource;
}

- (NSMutableArray<BVWorkoutModel *> *)workOutDataSource {
    if (!_workOutDataSource) {
        _workOutDataSource = [NSMutableArray array];
    }
    return _workOutDataSource;
}

- (NSMutableArray<BVHomeLocationView *> *)locationViews {
    if (!_locationViews) {
        _locationViews = [NSMutableArray array];
    }
    return _locationViews;
}

@end
